package com.dp.service.impl3;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.ChannelVo;
import com.dp.pojo.JsonPage;
import com.dp.util.DataMap;
import com.dp.util.KeyGenerator;
import com.dp.vo.TChannels;
import com.dp.vo.TServiceInfo;

@Service
@Transactional
public class ChannelServiceImpl extends BaseImpl {

	
	/**
	 * 一级栏目记录数,用户所属机构关联的一级栏目
	 * @return
	 */
	public List<ChannelVo> findChannelidS(DataMap hashMap){
		/*Object user_id = hashMap.get("user_id");
		List<ChannelVo> result=new ArrayList<ChannelVo>();
		try {
	        this.init();
	        this.sql="select tsc.channelid,tc.channel_name from t_spcode_channel tsc,t_channels tc where tsc.channelid=tc.channel_id and spcode=(select te.sp_code from t_employee te join t_user tu on te.employee_id=tu.employee_id where user_id='"+user_id+"')";
	        rs1=stmt.executeQuery(sql);
	        ChannelVo channel=null;
			while(rs1.next()){
				channel=new ChannelVo();
				channel.setChannel_id(rs1.getString(1));
				channel.setChannelName(rs1.getString(2));
				result.add(channel);
			}
			this.closeAll();
		}catch (Exception e) {
				logger.error("findChannelidS fail !!!" + e.getMessage());
				e.printStackTrace();
				if(conn!=null){
					try {
						conn.rollback();
					} catch (SQLException e1) {
						e1.printStackTrace();
					} 
				}
		} finally {
			this.closeAll();
		}
	        return result;*/
		
		Object user_id = hashMap.get("user_id");
		List<ChannelVo> result=new ArrayList<ChannelVo>();
		try {
	        this.sql="select tsc.channelid,tc.channel_name from t_spcode_channel tsc,t_channels tc where tsc.channelid=tc.channel_id and spcode=(select te.sp_code from t_employee te join t_user tu on te.employee_id=tu.employee_id where user_id='"+user_id+"')";
	        List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
	        ChannelVo channel=null;
	        for(Object[]o:temp)
			{
				channel=new ChannelVo();
				channel.setChannel_id(this.getString(o[0]));
				channel.setChannelName(this.getString(o[1]));
				result.add(channel);
			}
		}catch (Exception e) {
				logger.error("findChannelidS fail !!!" + e.getMessage());
				e.printStackTrace();
		} 
	    return result;
	}
	
	/**
	 * 二级栏目记录数
	 * @return
	 */
	public int getFirstLevelCount(DataMap hashMap){
		/*int ans = 0;
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
	    String firChannelid=(String)hashMap.get("firChannelid");
		try {
	        this.init();
			this.sql="SELECT count(tc.channel_id) FROM t_channels tc " +
		" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level != 1";
			if(!"root".equals(user_id)){
				sql="SELECT count(tc.channel_id) FROM t_channels tc " +
				" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and previous_id ='"+firChannelid+"'";
			}
			rs1=stmt.executeQuery(sql);
			if(rs1.next()){
				ans = rs1.getInt(1);
			}
			closeAll();
		 }catch (Exception e) {
				logger.error("getFirstLevelCount fail !!!" + e.getMessage());
				e.printStackTrace();
				if(conn!=null){
					try {
						conn.rollback();
					} catch (SQLException e1) {
						e1.printStackTrace();
					} 
				}
		} finally {
			this.closeAll();
		}
		return ans;*/
		
		int ans = 0;
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
	    String firChannelid=(String)hashMap.get("firChannelid");
	    try { 
	    sql="select channel_id from t_channels where channel_name='news' and status='ENABLED'";
	    String s=this.getOneString();
		
			this.sql="SELECT count(tc.channel_id) FROM t_channels tc " +
		" where primal_id ='" +s+"'"+
		" and  previous_id ='" +s+"' and level != 1";
			if(!"root".equals(user_id)){
				sql="SELECT count(tc.channel_id) FROM t_channels tc " +
				" where primal_id ='" +s+"'" +
				"  and previous_id ='"+firChannelid+"'";
			}
			ans=this.getOneInt();
		 }catch (Exception e) {
				logger.error("getFirstLevelCount fail !!!" + e.getMessage());
				e.printStackTrace();
		} 
		return ans;
	}	
	
	public List getListByParent(String parentId){
		/*List ans = new ArrayList();
		ChannelVo cv=null;
		try {
			this.init();
			String sql = "SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.status,tc.channel_type,tc.previous_id,tc.service_code FROM t_channels tc WHERE  primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') and tc.previous_id = '"+parentId+"'";
			rs1=stmt.executeQuery(sql);
				sql="SELECT T.previous_id FROM t_channels T WHERE  T.previous_id =?";
			prep=conn.prepareStatement(sql);
				sql="SELECT nf.channelid,nf.service_code FROM news_extends_firstchannel nf WHERE  nf.channel_id =?";
			prep1=conn.prepareStatement(sql);
				sql="SELECT nc.channleid FROM news_extends_channel nc WHERE  nc.channel_id =?";
			prep2=conn.prepareStatement(sql);
			boolean isNormal=false;
			while(rs1.next()){
				cv = new ChannelVo();
				cv.setChannel_id(rs1.getString("channel_id"));
				cv.setChannelName(rs1.getString("channel_name"));
				cv.setFunctionName(rs1.getString("function_name"));
				cv.setChannelType(rs1.getString("channel_type"));
				cv.setPreviousId(rs1.getString("previous_id"));
				cv.setStatus(rs1.getString("status"));
				prep.setString(1, cv.getChannel_id());
				rs2=prep.executeQuery();
				String isLeaf="0";
				if(rs2.next()){
					isLeaf="1";
				}
				if("NORMAL".equals(cv.getFunctionName())||"CHANNELSONG".equals(cv.getFunctionName())){
					isNormal=true;
				}
				if(isNormal){
					prep1.setString(1, cv.getChannel_id());
					rs2=prep1.executeQuery();
					if(rs2.next()){
						cv.setChannelid(rs2.getString("channelid"));
						cv.setServiceCode(rs2.getString("service_code"));
					}
				}else{
					prep2.setString(1, cv.getChannel_id());
					rs2=prep2.executeQuery();
					if(rs2.next()){
						cv.setChannelid(rs2.getString("channleid"));
						cv.setServiceCode(rs1.getString("service_code"));
					}
				}
				cv.setIsLeaf(isLeaf);
				
				ans.add(cv);
			}
			closeAll();
		}catch (Exception e) {
			logger.error("getFirstLevelCount fail !!!" + e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
		} finally {
			this.closeAll();
		}
		return ans;*/
		
		List ans = new ArrayList();
		ChannelVo cv=null;
		try {
			 sql = "SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.status,tc.channel_type,tc.previous_id,tc.service_code FROM t_channels tc WHERE  primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') and tc.previous_id = '"+parentId+"'";
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
				sql="SELECT nf.channelid,nf.service_code FROM news_extends_firstchannel nf WHERE  nf.channel_id =?";
			Query query1=em.createNativeQuery(sql);
				sql="SELECT nc.channleid FROM news_extends_channel nc WHERE  nc.channel_id =?";
			Query query2=em.createNativeQuery(sql);
			boolean isNormal=false;
			for(Object[]o:temp)
			{
				cv = new ChannelVo();
				cv.setChannel_id(this.getString(o[0]));
				cv.setChannelName(this.getString(o[1]));
				cv.setFunctionName(this.getString(o[2]));
				cv.setStatus(this.getString(o[3]));
				cv.setChannelType(this.getString(o[4]));
				cv.setPreviousId(this.getString(o[5]));
				
				String isLeaf="0";
				sql="SELECT count(*) FROM t_channels T WHERE  T.previous_id ='"+this.getString(o[0])+"'";
				if(this.getOneInt()>0){
					isLeaf="1";
				}
				if("NORMAL".equals(cv.getFunctionName())||"CHANNELSONG".equals(cv.getFunctionName())){
					isNormal=true;
				}
				if(isNormal){
					query1.setParameter(1, cv.getChannel_id());
					List<Object[]> temp1=query1.getResultList();//this.em.createNativeQuery(sql).getResultList();
					if(temp1.size()>0){
						cv.setChannelid(this.getString(temp1.get(0)[0]));
						cv.setServiceCode(this.getString(temp1.get(0)[1]));
					}
				}else{
					query2.setParameter(1, cv.getChannel_id());
					List<Object[]> temp2=query2.getResultList();//this.em.createNativeQuery(sql).getResultList();
					if(temp2.size()>0){
						cv.setChannelid(this.getString(temp2.get(0)));
						cv.setServiceCode(this.getString(o[6]));
					}
				}
				cv.setIsLeaf(isLeaf);
				
				ans.add(cv);
			}
		}catch (Exception e) {
			logger.error("getFirstLevelCount fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return ans;
	}
	
	public List getList(DataMap hashMap,int start,int end){
		/*List ans = new ArrayList();
		ChannelVo cv=null;
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
	    String firChannelid=(String)hashMap.get("firChannelid");
		try {
			this.init();
			this.sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.status,tc.channel_type,tc.level,tc.previous_id,(case when nf.service_code is null then tc.service_code else nf.service_code end ) as service_code,nf.channelid FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
			" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level != 1" ;
			if(!"root".equals(user_id)){
				sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.status,tc.channel_type,tc.level,tc.previous_id,(case when nf.service_code is null then tc.service_code else nf.service_code end ) as service_code,nf.channelid FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
				" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id ='"+firChannelid+"'";
			}
			sql +=" order by tc.created_date";
			sql +=" limit "+start+" ,"+(end-start);
			prep=conn.prepareStatement(sql);
			rs1=prep.executeQuery();
			this.sql="SELECT T.previous_id FROM t_channels T WHERE  T.previous_id =?";
			prep2=conn.prepareStatement(sql);
			while(rs1.next()){
				cv=new ChannelVo();
				cv.setChannel_id(rs1.getString("channel_id"));
				cv.setChannelName(rs1.getString("channel_name"));
				cv.setFunctionName(rs1.getString("function_name"));
				cv.setChannelType(rs1.getString("channel_type"));
				cv.setPreviousId(rs1.getString("previous_id"));
				cv.setServiceCode(rs1.getString("service_code"));
				cv.setChannelid(rs1.getString("channelid"));
				cv.setStatus(rs1.getString("status"));
				prep2.setString(1, cv.getChannel_id());
				rs2=prep2.executeQuery();
				String isLeaf="0";
				if(rs2.next()){
					isLeaf="1";
				}
				cv.setIsLeaf(isLeaf);
				ans.add(cv);
			}
			closeAll();
		} catch (Exception e) {
			logger.error("getFirstLevelCount fail !!!" + e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
		} finally {
			this.closeAll();
		}
		return ans;*/
		
		List ans = new ArrayList();
		ChannelVo cv=null;
		Object role_id = hashMap.get("role_id");
	    Object user_id = hashMap.get("user_id");
	    String firChannelid=(String)hashMap.get("firChannelid");
		try {
			this.sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.status,tc.channel_type,tc.level,tc.previous_id,(case when nf.service_code is null then tc.service_code else nf.service_code end ) as service_code,nf.channelid FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
			" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')" +
			"  and  previous_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level != 1" ;
			if(!"root".equals(user_id)){
				sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.status,tc.channel_type,tc.level,tc.previous_id,(case when nf.service_code is null then tc.service_code else nf.service_code end ) as service_code,nf.channelid FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
				" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') " +
				" and  previous_id ='"+firChannelid+"'";
			}
			sql +=" order by tc.created_date";
			sql +=" limit "+start+" ,"+(end-start);
			
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp)
			{
				cv=new ChannelVo();
				cv.setChannel_id(this.getString(o[0]));
				cv.setChannelName(this.getString(o[1]));
				cv.setFunctionName(this.getString(o[2]));
				cv.setStatus(this.getString(o[3]));
				cv.setChannelType(this.getString(o[4]));
				cv.setPreviousId(this.getString(o[5]));
				cv.setServiceCode(this.getString(o[6]));
				cv.setChannelid(this.getString(o[7]));
				
				String isLeaf="0";
				this.sql="SELECT count(*) FROM t_channels T WHERE  T.previous_id ='"+this.getString(o[0])+"'";
				if(this.getOneInt()!=0){
					isLeaf="1";
				}
				cv.setIsLeaf(isLeaf);
				ans.add(cv);
			}
		} catch (Exception e) {
			logger.error("getFirstLevelCount fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return ans;
	}
	
	/*public String isLeaf(String id) {
		try {
	        this.init();
			this.sql="SELECT T.previous_id FROM t_channels T WHERE  T.previous_id ='"
						+ id + "'";
			rs1=stmt.executeQuery(sql);
			if(rs1.next()){
				return "1";
			}
		 }catch (Exception e) {
				logger.error("getFirstLevelCount fail !!!" + e.getMessage());
				e.printStackTrace();
				if(conn!=null){
					try {
						conn.rollback();
					} catch (SQLException e1) {
						e1.printStackTrace();
					} 
				}
		} finally {
			this.closeAll();
		}
		return "0";
	}*/
	
	public String getNewsChannelId()
	{
		this.sql = "SELECT channel_id FROM t_channels t where channel_name='news' and level=1";
		try {
			return this.queryOne(sql);
		} catch (Exception e) {
			logger.error(" getNewsChannelId fail !!!" +e.getMessage());
			e.printStackTrace();
			return "";
		}
	}
	
	public String getChildFuncName(String chid)
	{
		this.sql = "SELECT function_name FROM t_channels t where previous_id='"+chid+"' and channel_name!='news' limit 1";
		try {
			return this.queryOne(sql);
		} catch (Exception e) {
			logger.error(" getChildFuncName fail !!!" +e.getMessage());
			e.printStackTrace();
			return "";
		}
	}
	
	public boolean addChannel(TChannels newch,TChannels oldch)
	{
		String channel_id = KeyGenerator.getInstance().getNextKeyValue("t_channels");
		String chiddb = ObjectToStringDB(channel_id);
		String servicecode = ObjectToStringDB(newch.getServiceCode());
		String chname = ObjectToStringDB(newch.getChannelName());
		String channel_comment = ObjectToStringDB(newch.getChannelComment());
		String function_name = ObjectToStringDB(newch.getFunctionName());
		String previous_id = ObjectToStringDB(oldch.getChannelId());
		String primal_id = ObjectToStringDB(oldch.getPrimalId());
		String level = ObjectToStringDB((Integer.parseInt(oldch.getLevel())+1));
		String channel_type = ObjectToStringDB(newch.getChannelType());
		String channel_classifying_label = ObjectToStringDB(newch.getChannelClassifyingLabel());
		String channel_hot_topics = ObjectToStringDB(newch.getChannelHotTopics());
		ArrayList<String> sqlList = new ArrayList<String>();
		//insert servicecode = null 
		
			this.sql = "insert into t_channels(channel_id,service_code,channel_name,channel_comment,function_name,status,ordered,created_date," +
			"previous_id,primal_id,level,channel_type,channel_hot_topics,channel_classifying_label) " +
			"values("+chiddb+","+servicecode+","+chname+","+channel_comment+","+function_name+",'ENABLED'," +
			"0,now(),"+previous_id+","+primal_id+","+level+","+channel_type+","+channel_hot_topics+","+channel_classifying_label+")";
			this.log.info("addChannel impl3 insert t_channels:"+this.sql);
			em.createNativeQuery(sql).executeUpdate();
			if("NORMAL".equalsIgnoreCase(newch.getFunctionName()))
			{
				//insert news_extends_firstchannel
				this.sql = "INSERT INTO news_extends_firstchannel(channel_id,channeltype,service_code) VALUES("+chiddb+",3,"+servicecode+")";
				this.log.info("addChannel NORMAL impl3 insert news_extends_firstchannel:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
				//insert news_contenttype
				String temp = newch.getChannelName()+"."+channel_id;
				temp = ObjectToStringDB(temp);
				this.sql = "INSERT INTO news_contenttype(newscontenttype,channelid,channel_id) VALUES("+temp+",(select LAST_INSERT_ID()),"+chiddb+")";
				this.log.info("addChannel NORMAL impl3 insert news_contenttype:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
				//insert news_buttons
				this.sql = "INSERT INTO news_buttons(buttonname,buttontext,buttoncontenttype,buttontype)VALUES("+chname+","+chname+","+temp+",3)";
				this.log.info("addChannel NORMAL impl3 insert news_buttons:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
				//insert news_extends_firstchannel_buttons
				this.sql = "INSERT INTO news_extends_firstchannel_buttons(channelid,buttonid) SELECT b.channelid,(select LAST_INSERT_ID()) " +
						"FROM news_extends_firstchannel b WHERE b.channel_id="+previous_id;
				this.log.info("addChannel NORMAL impl3 insert news_extends_firstchannel_buttons:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
			}
			if("LAST".equalsIgnoreCase(newch.getFunctionName()))
			{
				//insert news_extends_channel
				this.sql = "INSERT INTO news_extends_channel(channel_id,updatetimer) VALUES ("+chiddb+",'0')";
				this.log.info("addChannel LAST impl3 insert news_extends_channel:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
				//insert news_extends_firstchannel_channels
				this.sql = "INSERT INTO news_extends_firstchannel_channels(channelid,channleid) " +
						"SELECT b.channelid,(select LAST_INSERT_ID()) FROM news_extends_firstchannel b WHERE b.channel_id="+previous_id;
				this.log.info("addChannel LAST impl3 insert news_extends_firstchannel_channels:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
			}
			
		
		return true;
		
		/*try {
			this.init();
			this.sql = "insert into t_channels(channel_id,service_code,channel_name,channel_comment,function_name,status,ordered,created_date," +
			"previous_id,primal_id,level,channel_type,channel_hot_topics,channel_classifying_label) " +
			"values("+chiddb+","+servicecode+","+chname+","+channel_comment+","+function_name+",'ENABLED'," +
			"0,now(),"+previous_id+","+primal_id+","+level+","+channel_type+","+channel_classifying_label+","+channel_hot_topics+")";
			this.log.info("addChannel impl3 insert t_channels:"+this.sql);
			stmt=conn.createStatement();
			stmt.executeUpdate(sql);
			if("NORMAL".equalsIgnoreCase(newch.getFunctionName()))
			{
				//insert news_extends_firstchannel
				this.sql = "INSERT INTO news_extends_firstchannel(channel_id,channeltype,service_code) VALUES("+chiddb+",3,"+servicecode+")";
				this.log.info("addChannel NORMAL impl3 insert news_extends_firstchannel:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
				//insert news_contenttype
				String temp = newch.getChannelName()+"."+channel_id;
				temp = ObjectToStringDB(temp);
				this.sql = "INSERT INTO news_contenttype(newscontenttype,channelid,channel_id) VALUES("+temp+",(select LAST_INSERT_ID()),"+chiddb+")";
				this.log.info("addChannel NORMAL impl3 insert news_contenttype:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
				//insert news_buttons
				this.sql = "INSERT INTO news_buttons(buttonname,buttontext,buttoncontenttype,buttontype)VALUES("+chname+","+chname+","+temp+",3)";
				this.log.info("addChannel NORMAL impl3 insert news_buttons:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
				//insert news_extends_firstchannel_buttons
				this.sql = "INSERT INTO news_extends_firstchannel_buttons(channelid,buttonid) SELECT b.channelid,(select LAST_INSERT_ID()) " +
						"FROM news_extends_firstchannel b WHERE b.channel_id="+previous_id;
				this.log.info("addChannel NORMAL impl3 insert news_extends_firstchannel_buttons:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
			}
			if("LAST".equalsIgnoreCase(newch.getFunctionName()))
			{
				//insert news_extends_channel
				this.sql = "INSERT INTO news_extends_channel(channel_id,updatetimer) VALUES ("+chiddb+",'0')";
				this.log.info("addChannel LAST impl3 insert news_extends_channel:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
				//insert news_extends_firstchannel_channels
				this.sql = "INSERT INTO news_extends_firstchannel_channels(channelid,channleid) " +
						"SELECT b.channelid,(select LAST_INSERT_ID()) FROM news_extends_firstchannel b WHERE b.channel_id="+previous_id;
				this.log.info("addChannel LAST impl3 insert news_extends_firstchannel_channels:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
			}
			
			closeAll();
		} catch (Exception e) {
			logger.error("getFirstLevelCount fail !!!" + e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
			return false;
		} finally {
			this.closeAll();
		}
		return true;*/
		
		
		/*
		this.sql = "insert into t_channels(channel_id,service_code,channel_name,channel_comment,function_name,status,ordered,created_date," +
			"previous_id,primal_id,level,channel_type,channel_hot_topics,channel_classifying_label) " +
			"values("+chiddb+","+servicecode+","+chname+","+channel_comment+","+function_name+",'ENABLED'," +
			"0,now(),"+previous_id+","+primal_id+","+level+","+channel_type+","+channel_classifying_label+","+channel_hot_topics+")";
		this.log.info("addChannel impl3 insert t_channels:"+this.sql);
		sqlList.add(this.sql);
		if("NORMAL".equalsIgnoreCase(newch.getFunctionName()))
		{
			//insert news_extends_firstchannel
			this.sql = "INSERT INTO news_extends_firstchannel(channel_id,channeltype,service_code) VALUES("+chiddb+",3,"+servicecode+")";
			this.log.info("addChannel NORMAL impl3 insert news_extends_firstchannel:"+this.sql);
			sqlList.add(this.sql);
			//insert news_contenttype
			String temp = newch.getChannelName()+"."+channel_id;
			temp = ObjectToStringDB(temp);
			this.sql = "INSERT INTO news_contenttype(newscontenttype,channelid,channel_id) VALUES("+temp+",(select LAST_INSERT_ID()),"+chiddb+")";
			this.log.info("addChannel NORMAL impl3 insert news_contenttype:"+this.sql);
			sqlList.add(this.sql);
			//insert news_buttons
			this.sql = "INSERT INTO news_buttons(buttonname,buttontext,buttoncontenttype,buttontype)VALUES("+chname+","+chname+","+temp+",3)";
			this.log.info("addChannel NORMAL impl3 insert news_buttons:"+this.sql);
			sqlList.add(this.sql);
			//insert news_extends_firstchannel_buttons
			this.sql = "INSERT INTO news_extends_firstchannel_buttons(channelid,buttonid) SELECT b.channelid,(select LAST_INSERT_ID()) " +
					"FROM news_extends_firstchannel b WHERE b.channel_id="+previous_id;
			this.log.info("addChannel NORMAL impl3 insert news_extends_firstchannel_buttons:"+this.sql);
			sqlList.add(this.sql);
		}
		if("LAST".equalsIgnoreCase(newch.getFunctionName()))
		{
			//insert news_extends_channel
			this.sql = "INSERT INTO news_extends_channel(channel_id,updatetimer) VALUES ("+chiddb+",'0')";
			this.log.info("addChannel LAST impl3 insert news_extends_channel:"+this.sql);
			sqlList.add(this.sql);
			//insert news_extends_firstchannel_channels
			this.sql = "INSERT INTO news_extends_firstchannel_channels(channelid,channleid) " +
					"SELECT b.channelid,(select LAST_INSERT_ID()) FROM news_extends_firstchannel b WHERE b.channel_id="+previous_id;
			this.log.info("addChannel LAST impl3 insert news_extends_firstchannel_channels:"+this.sql);
			sqlList.add(this.sql);
		}
		try {
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			this.log.error("addChannel impl3 error!!!"+e.getMessage());
			e.printStackTrace();
			return false;
		}*/
	}
	
	
	public boolean editChannel(TChannels oldch)
	{
		String channel_id = oldch.getChannelId();
		String chiddb = ObjectToStringDB(oldch.getChannelId());
		String chname = ObjectToStringDB(oldch.getChannelName());
		String channel_comment = ObjectToStringDB(oldch.getChannelComment());
		String channel_type = ObjectToStringDB(oldch.getChannelType());
		String channel_classifying_label = ObjectToStringDB(oldch.getChannelClassifyingLabel());
		String channel_hot_topics = ObjectToStringDB(oldch.getChannelHotTopics());
		ArrayList<String> sqlList = new ArrayList<String>();
			this.sql = "update t_channels set channel_name="+chname+",channel_comment="+channel_comment+",channel_type="+channel_type+
				",channel_classifying_label="+channel_classifying_label+",channel_hot_topics="+channel_hot_topics+" where channel_id="+chiddb;
			this.log.info("editChannel impl3 update t_channels:"+this.sql);
			em.createNativeQuery(sql).executeUpdate();
			if("NORMAL".equalsIgnoreCase(oldch.getFunctionName()))
			{
				String temp = oldch.getChannelName()+"."+channel_id;
				temp = ObjectToStringDB(temp);
				//update news_buttons
				this.sql = "update news_buttons set buttonname="+chname+",buttontext="+chname+",buttoncontenttype="+temp+
				" where buttoncontenttype=(SELECT newscontenttype FROM news_contenttype where channel_id="+chiddb+")";
				this.log.info("editChannel NORMAL impl3 update news_buttons:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
				//update news_contenttype
				this.sql = "update news_contenttype set newscontenttype="+temp+" where channel_id="+chiddb;
				this.log.info("editChannel NORMAL impl3 update news_contenttype:"+this.sql);
				em.createNativeQuery(sql).executeUpdate();
			}
		
		return true;
		
		/*try {
			this.init();
			this.sql = "update t_channels set channel_name="+chname+",channel_comment="+channel_comment+",channel_type="+channel_type+
				",channel_classifying_label="+channel_classifying_label+",channel_hot_topics="+channel_hot_topics+" where channel_id="+chiddb;
			this.log.info("editChannel impl3 update t_channels:"+this.sql);
			stmt=conn.createStatement();
			stmt.executeUpdate(sql);
			if("NORMAL".equalsIgnoreCase(oldch.getFunctionName()))
			{
				String temp = oldch.getChannelName()+"."+channel_id;
				temp = ObjectToStringDB(temp);
				//update news_buttons
				this.sql = "update news_buttons set buttonname="+chname+",buttontext="+chname+",buttoncontenttype="+temp+
				" where buttoncontenttype=(SELECT newscontenttype FROM news_contenttype where channel_id="+chiddb+")";
				this.log.info("editChannel NORMAL impl3 update news_buttons:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
				//update news_contenttype
				this.sql = "update news_contenttype set newscontenttype="+temp+" where channel_id="+chiddb;
				this.log.info("editChannel NORMAL impl3 update news_contenttype:"+this.sql);
				stmt=conn.createStatement();
				stmt.executeUpdate(sql);
			}
			conn.commit(); 
		} catch (Exception e) {
			this.log.error("editChannel impl3 error!!!"+e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
			return false;
		}
		return true;*/
		
		/*
		this.sql = "update t_channels set channel_name="+chname+",channel_comment="+channel_comment+",channel_type="+channel_type+
			",channel_classifying_label="+channel_classifying_label+",channel_hot_topics="+channel_hot_topics+" where channel_id="+chiddb;
		this.log.info("editChannel impl3 update t_channels:"+this.sql);
		sqlList.add(this.sql);
		if("NORMAL".equalsIgnoreCase(oldch.getFunctionName()))
		{
			String temp = oldch.getChannelName()+"."+channel_id;
			temp = ObjectToStringDB(temp);
			//update news_buttons
			this.sql = "update news_buttons set buttonname="+chname+",buttontext="+chname+",buttoncontenttype="+temp+
			" where buttoncontenttype=(SELECT newscontenttype FROM news_contenttype where channel_id="+chiddb+")";
			this.log.info("editChannel NORMAL impl3 update news_buttons:"+this.sql);
			sqlList.add(this.sql);
			//update news_contenttype
			this.sql = "update news_contenttype set newscontenttype="+temp+" where channel_id="+chiddb;
			this.log.info("editChannel NORMAL impl3 update news_contenttype:"+this.sql);
			sqlList.add(this.sql);
		}
		try {
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			this.log.error("editChannel impl3 error!!!"+e.getMessage());
			e.printStackTrace();
			return false;
		}*/
	}
	
	public boolean assignChannelToUserWithEmpid(String empId,String[] selChidList)
	{
		ArrayList<String> sqlStrList = new ArrayList<String>();
		this.sql = "delete from t_user_channels where employee_id='"+empId+"'";
		this.log.info("assignChannelToUserWithEmpid delete t_user_channels:"+this.sql);
		sqlStrList.add(this.sql);
		for (int i = 0; i < selChidList.length; i++) 
		{
			sql = "insert into t_user_channels values ('"+selChidList[i]+"','"+empId+"')";
			this.log.info("assignChannelToUserWithEmpid insert into t_user_channels:"+this.sql);
			sqlStrList.add(sql);
		}
		try {
			return execTransaction(sqlStrList);
        } catch (Exception e) {
        	log.info(" assignChannelToUserWithEmpid impl3 error !!!" +e.getMessage());
            return false;
        }
	}
	
	public boolean delChannel(TChannels tchannels) 
	{
		String channel_id=tchannels.getChannelId();
		String channel_name=tchannels.getChannelName();
		String function_name=tchannels.getFunctionName();
		ArrayList<String> sqlList = new ArrayList<String>();
			if(function_name.equalsIgnoreCase("NORMAL") && channel_id!=null)
	    	{
				String buttonname = channel_name+"."+channel_id;
				sql="SELECT buttonid FROM NewsButtons where buttoncontenttype='"+buttonname+"'";
				Query query = em.createQuery(sql);
				List<Integer> buttonidL =em.createQuery(sql).getResultList();
				for(Integer buttonid:buttonidL){
					//删除关联关系
					this.sql = "delete from news_extends_firstchannel_buttons where buttonid="+buttonid+"";
		    		this.log.info("delChannel impl3 delete news_extends_firstchannel_buttons:"+this.sql);
		    		em.createNativeQuery(sql).executeUpdate();
				}
	    		
	    		this.sql = "delete from news_contenttype where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete news_contenttype:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    		
	    		this.sql = "delete from news_extends_firstchannel where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete news_extends_firstchannel:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    		
	    		this.sql = "delete from news_buttons where buttoncontenttype='"+buttonname+"'";
	    		this.log.info("delChannel impl3 delete news_buttons:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    		
	    		this.sql = "delete from t_channels where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete t_channels:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    	}
	    	else if(function_name.toUpperCase().equals("CHANNELSONG")||function_name.toUpperCase().equals("LAST"))
	    	{
	    		String hql="SELECT channleid FROM NewsExtendsChannel where channelId.channelId='"+channel_id+"'";
				Query query = em.createQuery(hql);
				Object channleid =null;
				try {
					channleid = query.getSingleResult();
				} catch (NoResultException ex) {
					return false;
				} catch (NonUniqueResultException ex) {
					channleid = query.getResultList();
				}
	    		//删除关联关系
	    		this.sql = "delete from news_extends_firstchannel_channels where channleid="+channleid+"";
	    		this.log.info("delChannel impl3 delete news_extends_firstchannel_channels:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    		
	    		this.sql = "delete from news_extends_channel where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete news_extends_channel:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    		
	    		this.sql = "delete from t_channels where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete t_channels:"+this.sql);
	    		em.createNativeQuery(sql).executeUpdate();
	    	}
		
		return true;
		
		
		/*
		try {
			this.init();
			
			if(function_name.equalsIgnoreCase("NORMAL") && channel_id!=null)
	    	{
				String buttonname = channel_name+"."+channel_id;
				Object buttonid =null;
				this.sql = "SELECT buttonid FROM news_buttons where buttoncontenttype='"+buttonname+"'";
				rs1=stmt.executeQuery(sql);
				if(rs1.next()){
					buttonid = rs1.getInt(1);
				}
				//删除关联关系
				this.sql = "delete from news_extends_firstchannel_buttons where buttonid="+buttonid+"";
	    		this.log.info("delChannel impl3 delete news_extends_firstchannel_buttons:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    		this.sql = "delete from news_contenttype where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete news_contenttype:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    		this.sql = "delete from t_channels where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete t_channels:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    		this.sql = "delete from news_extends_firstchannel where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete news_extends_firstchannel:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    		this.sql = "delete from news_buttons where buttoncontenttype='"+buttonname+"'";
	    		this.log.info("delChannel impl3 delete news_buttons:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    	}
	    	else if(function_name.toUpperCase().equals("CHANNELSONG")||function_name.toUpperCase().equals("LAST"))
	    	{
	    		
	    		Object channleid =null;
	    		this.sql = "SELECT channleid FROM news_extends_channel where channel_id='"+channel_id+"'";
	    		rs1=stmt.executeQuery(sql);
				if(rs1.next()){
					channleid = rs1.getInt(1);
				}
	    		//删除关联关系
	    		this.sql = "delete from news_extends_firstchannel_channels where channleid="+channleid+"";
	    		this.log.info("delChannel impl3 delete news_extends_firstchannel_channels:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    		this.sql = "delete from t_channels where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete t_channels:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    		this.sql = "delete from news_extends_channel where channel_id='"+channel_id+"'";
	    		this.log.info("delChannel impl3 delete news_extends_channel:"+this.sql);
	    		stmt=conn.createStatement();
				stmt.executeUpdate(sql);
	    	}
			conn.commit(); 
		} catch (Exception e) {
			this.log.error("editChannel impl3 error!!!"+e.getMessage());
			e.printStackTrace();
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
			return false;
		}
		return true;*/
		
		/*
		if(function_name.equalsIgnoreCase("NORMAL") && channel_id!=null)
    	{
			String buttonname = channel_name+"."+channel_id;
			Object buttonid = this.getSingleResult("SELECT buttonid FROM NewsButtons where buttoncontenttype='"+buttonname+"'");
			//删除关联关系
			this.sql = "delete from news_extends_firstchannel_buttons where buttonid="+buttonid+"";
    		this.log.info("delChannel impl3 delete news_extends_firstchannel_buttons:"+this.sql);
    		sqlList.add(this.sql);
    		this.sql = "delete from news_contenttype where channel_id='"+channel_id+"'";
    		this.log.info("delChannel impl3 delete news_contenttype:"+this.sql);
    		sqlList.add(this.sql);
    		this.sql = "delete from t_channels where channel_id='"+channel_id+"'";
    		this.log.info("delChannel impl3 delete t_channels:"+this.sql);
    		sqlList.add(this.sql);
    		this.sql = "delete from news_extends_firstchannel where channel_id='"+channel_id+"'";
    		this.log.info("delChannel impl3 delete news_extends_firstchannel:"+this.sql);
    		sqlList.add(this.sql);
    		this.sql = "delete from news_buttons where buttoncontenttype='"+buttonname+"'";
    		this.log.info("delChannel impl3 delete news_buttons:"+this.sql);
    		sqlList.add(this.sql);
    	}
    	else if(function_name.toUpperCase().equals("CHANNELSONG")||function_name.toUpperCase().equals("LAST"))
    	{
    		
    		Object channleid = this.getSingleResult("SELECT channleid FROM NewsExtendsChannel where channelId.channelId='"+channel_id+"'");
    		//删除关联关系
    		this.sql = "delete from news_extends_firstchannel_channels where channleid="+channleid+"";
    		this.log.info("delChannel impl3 delete news_extends_firstchannel_channels:"+this.sql);
    		sqlList.add(this.sql);
    		this.sql = "delete from t_channels where channel_id='"+channel_id+"'";
    		this.log.info("delChannel impl3 delete t_channels:"+this.sql);
    		sqlList.add(this.sql);
    		this.sql = "delete from news_extends_channel where channel_id='"+channel_id+"'";
    		this.log.info("delChannel impl3 delete news_extends_channel:"+this.sql);
    		sqlList.add(this.sql);
    	}
		try {
			return execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" delChannel impl3 error !!!" +e.getMessage());
			return false;
		}*/
	}
	
	public boolean updateChannelStatus(TChannels tchannels,String status)
	{
		String channel_id=tchannels.getChannelId();
		String chiddb = ObjectToStringDB(channel_id);
		ArrayList<String> sqlList = new ArrayList<String>();
		this.sql = "update t_channels set status="+ObjectToStringDB(status)+" where channel_id="+chiddb;
		this.log.info("updateChannelStatus impl3 update t_channels:"+this.sql);
		sqlList.add(this.sql);
		if(status.equals("ENABLED"))
			this.sql = "insert into news_extends_firstchannel_channels values " +
					"((select channelid from news_extends_firstchannel where channel_id=" +
					"(select previous_id from t_channels where channel_id="+chiddb+"))," +
						"(select channleid from news_extends_channel where channel_id="+chiddb+"),0)";
		else
			this.sql = "delete from news_extends_firstchannel_channels where channelid=" +
				"(select channelid from news_extends_firstchannel where channel_id=" +
				"(select previous_id from t_channels where channel_id="+chiddb+")) and channleid=" +
				"(select channleid from news_extends_channel where channel_id="+chiddb+")";
		this.log.info("updateChannelStatus impl3 update news_extends_firstchannel_channels:"+this.sql);
		sqlList.add(this.sql);
		try {
			return execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" updateChannelStatus impl3 fail !!!" +e.getMessage());
			return false;
		}
	}
	/**
	 * 取得起始行和终止行.
	 * @param request 请求
	 * @param allCount 总行数
	 * @param pageSize 每页数目
	 * @return 整型数组
	 */
	public static int[] getStartAndEndInfo(HttpServletRequest request,
			int allCount, int pageSize) {
		//默认当前的页数是1
		int page = 1;
		//默认的分页行数就是传入的每页行数
		int limit = pageSize;
		//新的起始位置
		int newStart = 0;
		int newEnd = 0;
		//在点击翻页按钮的时候,会传递gtstart参数到后台.
		if (request.getParameter("gtpage") != null) {
			limit = Integer.parseInt(request.getParameter("gtlimit"));
			page = Integer.parseInt(request.getParameter("gtpage"));
		}
		//否则就说明是第一次进入页面进行的查询
		else {
			if (request.getParameter("gtlimit") != null)
				limit = Integer.parseInt(request.getParameter("gtlimit"));
		}
		request.setAttribute("gtlimit", limit);
		request.setAttribute("gtpage", page);
		request.setAttribute("gtcount", allCount);

		//如果是第一次显示,而且要显示分页栏,就说明只显示第一页之间的数据
		if (limit != -1) {
			return new int[] {
					(page - 1) * limit,
					(page * limit + 1) > allCount + 1 ? allCount + 1 : (page
							* limit) };
		}
		//说明是第一次显示页面,而且不用显示分页栏,就是要返回全部的数据.
		else {
			return new int[] { 0, allCount };
		}
	}
	
	public List<TChannels> getChannelsByNews(DataMap hashMap, Integer firstrow,Integer maxrow){
		TChannels tchannels=(TChannels) hashMap.get("tchannels");
		List<TChannels> tclist2=new ArrayList<TChannels>();
		List<TChannels> tclist3=new ArrayList<TChannels>();
		List<TChannels> result=null;
		TChannels tc=null;
		try {
			this.sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.channel_type,tc.level,tc.previous_id,(case when nf.service_code is null then tc.service_code else nf.service_code end ) as service_code FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
			" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level != 1 ";
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp)
			{
				tc=new TChannels();
				tc.setChannelId(this.getString(o[0]));
				tc.setChannelName(this.getString(o[1]));
				tc.setFunctionName(this.getString(o[2]));
				tc.setChannelType(this.getString(o[3]));
				tc.setLevel(this.getString(o[4]));
				tc.setPreviousId(this.getString(o[5]));
				tc.setServiceCode(this.getString(o[6]));
				tclist2.add(tc);
			}
			
			this.sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.channel_type,tc.level,tc.previous_id,(case when nf.service_code is null then tc.service_code else nf.service_code end ) as service_code FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
			" where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id !=(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level != 1 ";
			List<Object[]> temp1=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp1)
			{
				tc=new TChannels();
				tc.setChannelId(this.getString(o[0]));
				tc.setChannelName(this.getString(o[1]));
				tc.setFunctionName(this.getString(o[2]));
				tc.setChannelType(this.getString(o[3]));
				tc.setLevel(this.getString(o[4]));
				tc.setPreviousId(this.getString(o[5]));
				tc.setServiceCode(this.getString(o[6]));
				tclist3.add(tc);
			}
			
			if(tclist2!=null && tclist2.size()>0){
				result = new ArrayList<TChannels>(tclist2.size()+tclist3.size());
				List<TChannels> tc_templist=null;
				for(TChannels tc2:tclist2){
					
					tc_templist=new ArrayList<TChannels>();
					if(tclist3!=null && tclist3.size()>0){
						tc_templist = getTc_templist(tclist3,tc2,tc_templist);
					}
					//boolean bbchname=false;
					boolean bbchtype=false;
					if(tchannels!=null){
						if(tchannels.getChannelType().equals(tc2.getChannelType())){
							bbchtype=true;
						}else if("".equals(tchannels.getChannelType())){
							bbchtype=true;
						}
						for(TChannels tc_temp:tc_templist){
							/*if(tc_temp.getChannelName().indexOf(tchannels.getChannelName().toString().trim())!=-1){
								bbchname=true;
								break;
							}else */if("".equals(tchannels.getChannelName().toString().trim())){
								bbchtype=true;
								break;
							}
						}
						//if(bbchname&&bbchtype){
						if(bbchtype){
							result.addAll(tc_templist);
						}
					}else{
						result.addAll(tc_templist);
					}
					
				}
			}
		} catch (Exception e) {
			logger.error("getChannelsByNews fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return result;
	} 
	
	/**
	 * 第一个机构关联的一级栏目
	 * @param empid
	 * @return
	 */
	public String getChannelIdForSpcode(String empid)
	{
		String channel_id=null;
		this.sql = "select tsc.channelid from t_spcode_channel tsc where " +
				"spcode=(select te.sp_code from t_employee te where employee_id='"+empid+"')";
		try {
			channel_id=this.getOneString();
		} catch (Exception e) {
			logger.info(" getChannelIdForSpcode fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return channel_id;
	}
	
	private List<TChannels> getTc_templist(List<TChannels> tclist3,TChannels tc_temp,List<TChannels> tc_templist){
		tc_templist.add(tc_temp);
		for(TChannels tc3:tclist3){
			if(tc3.getPreviousId().equals(tc_temp.getChannelId())){
				getTc_templist(tclist3,tc3,tc_templist);
			}
		}
		return tc_templist;
	}
	
	public boolean setChannelBtn(String channel_id,String[] selected_btn)
	{
		ArrayList<String> sqlStrList = new ArrayList<String>();
		String sql = "delete from news_extends_firstchannel_buttons where channelid=" +
				"(SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"')";
		sqlStrList.add(sql);
		int count = 1;
		if (selected_btn != null) {
			for (int i = 0; i < selected_btn.length; i++) {
				String btnid = selected_btn[i];
				int btnorder = i+1;
				sql = "insert into news_extends_firstchannel_buttons values " +
						"((SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"' )," + btnid + "," + btnorder + ")";
				sqlStrList.add(sql);
				count++;
			}
		}
		String[] sqlStr = sqlStrList.toArray(new String[count]);
		try {
        	boolean bool = execTransaction(sqlStr);
            return bool;
        } catch (Exception e) {
        	logger.info(" setChannelBtn fail !!!" +e.getMessage());
            return false;
        }
	}
	
	public TChannels findTChannelsById(String channelId) {
		TChannels tc=null;
		try {
			this.sql="SELECT tc.channel_id,tc.channel_name,tc.channel_comment,tc.status,tc.function_name,tc.channel_type,tc.level,tc.previous_id," +
					"tc.primal_id,tc.channel_classifying_label,(case when nf.service_code is null then tc.service_code else nf.service_code end ) " +
					"as service_code FROM t_channels tc left join news_extends_firstchannel nf on nf.channel_id=tc.channel_id " +
					" where tc.channel_id='"+channelId+"'";
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp)
			{
				tc=new TChannels();
				tc.setChannelId(this.getString(o[0]));
				tc.setChannelName(this.getString(o[1]));
				tc.setChannelComment(this.getString(o[2]));
				tc.setStatus(this.getString(o[3]));
				tc.setFunctionName(this.getString(o[4]));
				tc.setChannelType(this.getString(o[5]));
				tc.setLevel(this.getString(o[6]));
				tc.setPreviousId(this.getString(o[7]));
				tc.setPrimalId(this.getString(o[8]));
				tc.setChannelClassifyingLabel(this.getString(o[9]));
				tc.setServiceCode(this.getString(o[10]));
			}
		 }catch (Exception e) {
				logger.error("getChannelsByNews fail !!!" + e.getMessage());
				e.printStackTrace();
		}
		return tc;
	}
	
	public ArrayList getSelectButtons(String channel_id) {
		String querySql = "SELECT nb.buttonid ,nb.buttontext ,nfb.buttonorder FROM " +
		"news_extends_firstchannel_buttons nfb,news_buttons nb where nfb.channelid=" +
		"(SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"') and nb.buttonid=nfb.buttonid " +
				"order by (case when nfb.buttonorder is null then 99999 else nfb.buttonorder end)";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getButtons fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public ArrayList getAllChButtons() {
		String querySql = "SELECT buttonid,buttonname,buttontext,buttonicon,buttoncontenttype,buttontype,buttonaction FROM news_buttons n where buttontype=3";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" get channel Buttons fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public ArrayList getAllFunctionButtons() {
		String querySql = "SELECT buttonid,buttonname,buttontext,buttonicon,buttoncontenttype,buttontype,buttonaction FROM news_buttons n where buttontype!=3 and buttontype!=4 order by buttontype ";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" get function Buttons fail !!!" +e.getMessage());
			return null;
		}
	}
	public ArrayList getAllPostButtons() {
		String querySql = "SELECT buttonid,buttonname,buttontext,buttonicon,buttoncontenttype,buttontype,buttonaction FROM news_buttons n where buttontype=4";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" get post Buttons fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public ArrayList getChildItems(DataMap dataMap) {
		String channel_id = dataMap.getMapData("channel_id");
    	String function_name = dataMap.getMapData("function_name");
    	String tmpSql = "";
    	String result = "";
    	String querySql = "";
    	ArrayList items = null;
    	try {
    		 if ((function_name.toUpperCase().equals("NORMAL")) && (channel_id != null))
    		 /*      */       {
    		 /* 1178 */         tmpSql = "SELECT count(*) FROM news_extends_firstchannel_channels where channelid=(SELECT nf.channelid FROM news_extends_firstchannel nf where nf.channel_id='" + 
    		 /* 1179 */           channel_id + "')";
    		 /* 1180 */         result = queryOne(tmpSql);
    		 /* 1181 */         if (!result.equals("0"))
    		 /*      */         {
    		 /* 1184 */           this.sql = ("SELECT channelid FROM news_extends_firstchannel where  channel_id='" + channel_id + "'");
    		 /* 1185 */           int chid = getOneInt();
    		 /*      */ 
    		 /* 1196 */           querySql = "SELECT  a.channleid ,c.channel_name,a.channelorder FROM news_extends_firstchannel_channels a,news_extends_channel b,t_channels c where a.channelid=" + 
    		 /* 1198 */             chid + " and a.channleid=b.channleid and " + 
    		 /* 1199 */             "b.channel_id=c.channel_id order by  (case when a.channelorder is null then 0 else a.channelorder end) ";
    		 /*      */ 
    		 /* 1206 */           items = queryALLResultSet(querySql);
    		 /* 1207 */           items.add("last");
    		 /*      */         }
    		 /*      */         else
    		 /*      */         {
    		 /* 1211 */           querySql = "SELECT nb.buttonid ,nb.buttontext ,nfb.buttonorder  FROM news_extends_firstchannel_buttons nfb,news_buttons nb where nfb.channelid=(SELECT channelid FROM news_extends_firstchannel where channel_id='" + 
    		 /* 1213 */             channel_id + "') and nb.buttonid=nfb.buttonid " + 
    		 /* 1214 */             "order by (case when nfb.buttonorder is null then 0 else nfb.buttonorder end)";
    		 /* 1215 */           items = queryALLResultSet(querySql);
    		 /* 1216 */           items.add("normal");
    		 /*      */         }
    		 /* 1218 */         return items;
    		 /*      */       }
    		 /* 1220 */       if ((function_name.toUpperCase().equals("CHANNELSONG")) || (function_name.toUpperCase().equals("LAST")))
    		 /*      */       {
    		 /* 1222 */         querySql = "SELECT nc.cid ,nc.contenttitle ,ncc.titleorder  from news_extends_channel_title ncc,news_extends_channel nch,news_contenttitle nc where (ncc.contentstatus=1 OR ncc.contentstatus=5 OR ncc.contentstatus=9 OR ncc.contentstatus=12) and ncc.istest=1 and nch.channel_id='" + 
    		 /* 1226 */           channel_id + "' and ncc.channleid=nch.channleid and ncc.cid=nc.cid and (ncc.titleorder>=0 or ncc.titleorder is null) order by " + 
    		 /* 1227 */           "(case when ncc.titleorder is null then 0 else ncc.titleorder end),nc.cid desc";
    		 /* 1228 */         items = queryALLResultSet(querySql);
    		 /* 1229 */         items.add("content");
    		 /* 1230 */         return items;
    		 /*      */       }
	    		logger.info(" Channel function is not NORMAL or LAST !!!");
	    		return null;
	    	
	    	
    	} catch (Exception e) {
    		logger.info(" getChildItems fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	public ArrayList getSelectTopItemsByCh_id(String channel_id,String function_name) {
		String querySql = "SELECT nc.cid as itemid,nc.contenttitle as itemname,ncc.titleorder as itemorder from " +
		"news_extends_channel_title ncc,news_extends_channel nch,news_contenttitle nc where " +
		//contentstatus=1 是已审核，contentstatus=5 //广告已审核
		"(ncc.contentstatus=1 OR ncc.contentstatus=5) and ncc.istest=1 and " + 
		"nch.channel_id='"+channel_id+"' and ncc.channleid=nch.channleid and ncc.cid=nc.cid and ncc.titleorder<0 order by " +
				"(case when ncc.titleorder is null then 0 else ncc.titleorder end),nc.cid desc";
		ArrayList items = new ArrayList();
		try {
			if(function_name.toUpperCase().equals("CHANNELSONG")||function_name.toUpperCase().equals("LAST"))//最后一级列内容 ch_21
	    	{
	    		items = queryALLResultSet(querySql);
	    	}
	    	else
	    	{
	    		logger.info(" Channel function is not NORMAL or LAST !!!");
	    	}
			
		} catch (Exception e) {
			logger.info(" getSelectTopItems fail !!!" +e.getMessage());
		}
		return items;
	}
	
	public ArrayList getAllTopItemsByByCh_id(String channel_id,String function_name) {
		String querySql = "SELECT nc.cid as itemid,nc.contenttitle as itemname,ncc.titleorder as itemorder from " +
		"news_extends_channel_title ncc,news_extends_channel nch,news_contenttitle nc where " +
		//contentstatus=1 是已审核，contentstatus=5 //广告已审核
		"(ncc.contentstatus=1 OR ncc.contentstatus=5) and ncc.istest=1 and " + 
		"nch.channel_id='"+channel_id+"' and ncc.channleid=nch.channleid and ncc.cid=nc.cid order by " +
				"(case when ncc.titleorder is null then 0 else ncc.titleorder end),nc.cid desc";
		ArrayList items = new ArrayList();
		try {
			if(function_name.toUpperCase().equals("CHANNELSONG")||function_name.toUpperCase().equals("LAST"))//最后一级列内容 ch_21
	    	{
	    		items = queryALLResultSet(querySql);
	    	}
	    	else
	    	{
	    		logger.info(" Channel function is not NORMAL or LAST !!!");
	    	}
			
		} catch (Exception e) {
			logger.info(" getSelectTopItems fail !!!" +e.getMessage());
		}
		return items;
	}
	
	
	public boolean setTopitemsByCh_id(String channel_id,String[] selected_cids)
	{
		ArrayList<String> sqlStrList = new ArrayList<String>();
		String sql = "update news_extends_channel_title set titleorder=0 where channleid=(select channleid from news_extends_channel where channel_id='"+channel_id+"') and titleorder<0";
		sqlStrList.add(sql);
		int count = 1;
		if (selected_cids != null) {
			int cidslen=selected_cids.length;
			for (int i = 0; i < cidslen; i++) {
				String cid = selected_cids[i];
				int titleorder = -(cidslen-i);
				sql = "update news_extends_channel_title set titleorder="+titleorder+" where channleid=(select channleid from news_extends_channel where channel_id='"+channel_id+"') and cid="+cid+"";
				sqlStrList.add(sql);
				count++;
			}
		}
		String[] sqlStr = sqlStrList.toArray(new String[count]);
		try {
        	boolean bool = execTransaction(sqlStr);
            return bool;
        } catch (Exception e) {
        	logger.info(" setChannelBtn fail !!!" +e.getMessage());
            return false;
        }
	}
	
	
	public String getChildItemsCount(TChannels tchannels) {
		String channel_id = tchannels.getChannelId();
    	String function_name = tchannels.getFunctionName();
    	String tmpSql = "";
    	String result = "";
    	try {
	    	if(function_name.toUpperCase().equals("NORMAL") && channel_id!=null)
	    	{
	    		//判断是否有最后一�?
	    		tmpSql = "SELECT count(*) FROM news_extends_firstchannel_channels where channelid=" +
	    				"(SELECT nf.channelid FROM news_extends_firstchannel nf where nf.channel_id='"+channel_id+"')";
				result = queryOne(tmpSql);
				//result = 0 没有最后一级 查button
				if(result.equals("0"))
				{
					tmpSql = "SELECT count(nb.buttonid) FROM " +
					"news_extends_firstchannel_buttons nfb,news_buttons nb where nfb.channelid=" +
					"(SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"') and nb.buttonid=nfb.buttonid ";
					result = queryOne(tmpSql);
				}
				return result;
	    	}
	    	else if(function_name.toUpperCase().equals("CHANNELSONG")||function_name.toUpperCase().equals("LAST"))//最后一级列内容 ch_21
	    	{
	    		tmpSql = "SELECT count(nc.contentid) from " +
	    				"news_extends_channel_title ncc,news_extends_channel nch,news_contenttitle nc where " +
	    				//contentstatus=1 是已审核，contentstatus=5 //广告已审核
	    				"(ncc.contentstatus=1 OR ncc.contentstatus=5 OR ncc.contentstatus=9 OR ncc.contentstatus=12) and ncc.istest=1 and " + 
	    				"nch.channel_id='"+channel_id+"' and ncc.channleid=nch.channleid and ncc.cid=nc.cid ";
	    		result = queryOne(tmpSql);
	    		return result;
	    	}
	    	else
	    	{
	    		logger.info(" Channel function is not NORMAL or LAST !!!");
	    		return null;
	    	}
	    	
    	} catch (Exception e) {
    		logger.info(" getChildItemsCount empl3 fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean sortChannelItems(DataMap dataMap) {
		String channel_id = dataMap.getMapData("channel_id");
    	String itemtype = dataMap.getMapData("itemtype");
    	StringTokenizer st=new StringTokenizer(dataMap.getMapData("gvalue"),"|");
    	String tmpSql = "";
    	int ordered = 0;
    	ArrayList sqlList = new ArrayList();
    	if(itemtype.equals("last"))//排最后一�?
    	{
    		while(st.hasMoreElements())
    		{
    			ordered=ordered+1;
    			tmpSql = "update news_extends_firstchannel_channels set channelorder="+ordered+" where channleid="+ObjectToStringDB(st.nextElement()) + 
    			" and channelid=(SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"')";
    			sqlList.add(tmpSql);
    		}
    	}
    	if(itemtype.equals("normal"))//排普通栏目按�?
    	{
    		while(st.hasMoreElements())
    		{
    			ordered=ordered+1;
    			tmpSql = "update news_extends_firstchannel_buttons set buttonorder="+ordered+" where buttonid="+ObjectToStringDB(st.nextElement()) + 
    			" and channelid=(SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"')";
    			sqlList.add(tmpSql);
    		}
    	}
    	if(itemtype.equals("content"))//排普通栏�?
    	{
    		while(st.hasMoreElements())
    		{
//    			System.out.println(st.nextElement());
    			ordered=ordered+1;
    			tmpSql = "update news_extends_channel_title set titleorder="+ordered+" where cid="+st.nextElement()+" and channleid=(SELECT channleid FROM news_extends_channel where channel_id='"+channel_id+"') and (titleorder>=0 or titleorder is null)";
    			sqlList.add(tmpSql);
    		}
    	}
    	try {
			return execTransaction(sqlList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(" sortChannelItems fail !!!" +e.getMessage());
			return false;
		}
	}
	
	
	public int priceListCount(DataMap hashMap){
		int result = 0; 
		String role_id = hashMap.getMapData("role_id");
		String user_id = hashMap.getMapData("user_id");
		String userids = (String)hashMap.get("userids");
		StringBuffer sqlS = new StringBuffer("SELECT count(distinct ts.serviceid) FROM t_service_info ts left join " +
				"(select tup.service_code,tu.user_id from t_user tu left join t_user_prices tup on tu.employee_id=tup.employee_id) tups " +
				"on ts.service_code=tups.service_code where 1=1 ");
		if(StringIsNotNull(role_id))
		{
			sqlS.append(" and tups.user_id='" + user_id +"' "); 
		}else if(userids!=null){
			sqlS.append(" and tups.user_id in (" + userids +") "); 
		}
		List<TServiceInfo> tslist=new ArrayList<TServiceInfo>();
		TServiceInfo ts=null;
		try {
			sql=sqlS.toString();
			result=getOneInt();
		}catch (Exception e) {
			logger.error("priceListCount fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return result;
	}
	
	
	public List<TServiceInfo> priceList(DataMap hashMap,Integer firstrow,Integer maxrow){
		String role_id = hashMap.getMapData("role_id");
		String user_id = hashMap.getMapData("user_id");
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		String userids = (String)hashMap.get("userids");
		StringBuffer sqlS = new StringBuffer("SELECT distinct ts.serviceid,ts.service_code,ts.servicename,ts.price,ts.price_type,ts.servicetype FROM t_service_info ts left join " +
				"(select tup.service_code,tu.user_id from t_user tu left join t_user_prices tup on tu.employee_id=tup.employee_id) tups " +
				"on ts.service_code=tups.service_code where 1=1 ");
		if(StringIsNotNull(role_id))
		{
			sqlS.append(" and tups.user_id='" + user_id +"' "); 
		}else if(userids!=null){
			sqlS.append(" and tups.user_id in (" + userids +") "); 
		}
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord());
			}
		}
		if(firstrow!=null&&maxrow!=null){
			sqlS.append(" limit "+firstrow+","+maxrow+"");
		}
		List<TServiceInfo> tslist=new ArrayList<TServiceInfo>();
		TServiceInfo ts=null;
		try {
	        List<Object[]> temp=this.em.createNativeQuery(sqlS.toString()).getResultList();
			for(Object[]o:temp)
			{
				ts=new TServiceInfo();
				ts.setServiceid(Long.parseLong(this.getString(o[0])));
				ts.setServiceCode(this.getString(o[1]));
				ts.setServicename(this.getString(o[2]));
				ts.setPrice(new BigInteger(this.getString(o[3])));
				ts.setPriceType(this.getString(o[4]));
				ts.setServicetype(this.getString(o[5]));
				tslist.add(ts);
			}
		}catch (Exception e) {
			logger.error("priceList fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return tslist;
	}
	
	public boolean assignPriceChannelNews(DataMap dataMap)
	{
		String service_code = dataMap.getMapData("service_code");
		String channel_id = dataMap.getMapData("channel_id");
		String function_name = dataMap.getMapData("function_name");
		String sql = "";
		if(function_name!=null && (function_name.toUpperCase().equals("LAST") || function_name.toUpperCase().equals("CHANNELSONG")))
			sql = "update t_channels set service_code = '"+service_code+"' where channel_id = '"+channel_id+"'";
		else if(function_name!=null && function_name.toUpperCase().equals("NORMAL"))
			sql = "update news_extends_firstchannel set service_code = '"+service_code+"' where channel_id = '"+channel_id+"'";
		try {
			logger.debug("assignPriceChannelNews sql: "+sql);
			return execUpdate(sql);
		} catch (Exception e) {
			logger.info(" assignPriceChannelNews fail !!!" +e.getMessage());
			return false;
		}
	}
	
	public DataMap getCurrentIcon(String channel_id) {
		String querySql = "select nr.rid,nr.useragents,nr.name,nr.resourcetype,nr.url,nr.size,nr.rformat,nr.distributorid,nr.spcode,nr.isusebysys,nr.newformat,nr.fullpath" +
				" from news_resources nr where rid = (SELECT iconid FROM news_extends_channel where channel_id='"+channel_id+"')";
		DataMap a = null;
		try {
			a=(DataMap)queryALLResultSet(querySql).get(0);
			return a;
		} catch (Exception e) {
			logger.info(" getCurrentIcon fail !!!" +e.getMessage());
			return null;
		}
	}
	
//	public ArrayList getIconList() {
//		String querySql = "SELECT * FROM news_resources where isusebysys=1 and resourcetype=1";
//		try {
//			return queryALLResultSet(querySql);
//		} catch (Exception e) {
//			logger.info(" getCurrentIcon fail !!!" +e.getMessage());
//			return null;
//		}
//	}
	public DataMap getCurrentTimer(String channel_id) {
		try {
			String updatetimer = queryOne("SELECT updatetimer FROM news_extends_channel where channel_id='"+channel_id+"'");
			String querySql = "";
			DataMap a = new DataMap();
			if(updatetimer != null && !updatetimer.equals("0"))
			{
				querySql = "select tsa.timerid,tsa.timertime,tsa.timermsg,tsa.timequeue,tsa.isvalid" +
						" from t_sys_autoactivetimer tsa where timerid = (SELECT updatetimer FROM news_extends_channel where channel_id='"+channel_id+"')";
				a = (DataMap)queryALLResultSet(querySql).get(0);
			}
			if(updatetimer != null && updatetimer.equals("0"))
			{
				logger.info(" updatetimer = 0");
				a.put("timerid", "0");
			}
			return a;
		} catch (Exception e) {
			logger.info(" getCurrentIcon fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public ArrayList getTimerList() {
		String querySql = "SELECT t.timerid,t.timertime,t.timermsg,t.timequeue,t.isvalid  FROM t_sys_autoactivetimer t";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getCurrentIcon fail !!!" +e.getMessage());
			return null;
		}
	}
	public ArrayList getSelectAdsAtLastCh(String channel_id) {
		String querySql = "SELECT na.adid,na.adtitle, na.adtext FROM news_ads na,news_extends_channel_ads nca,news_extends_channel nc where " +
		"nc.channel_id='"+channel_id+"' and na.adid=nca.adid and nca.channleid=nc.channleid and na.adtype=1";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getSelectAdsAtLastCh fail !!!" +e.getMessage());
			return null;
		}
	}
	
	//add 1204 get news_extends_channel
	public DataMap getExtendsChannel(String channel_id) {
		String querySql = "SELECT channleid,channel_id,iconid,note,updatetimer,isshowtime,howshowtime,lastupdatetime,whichtag,isshowshort,isshowicon,titlenumber,channelurl" +
				" FROM news_extends_channel as t1 where channel_id="+ObjectToStringDB(channel_id);
		try {
			return (DataMap)queryALLResultSet(querySql).get(0);
		} catch (Exception e) {
			logger.info(" getExtendsChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public String getCurrentChannelType(String channel_id) {
		String querySql = "SELECT channeltype FROM news_extends_firstchannel where channel_id='"+channel_id+"'";
		try {
			return queryOne(querySql);
		} catch (Exception e) {
			logger.info(" getCurrentChannelType fail !!!" +e.getMessage());
			return null;
		}
	}
	
	//get ads by channel
	public  ArrayList getSelectAdsAtFstCh(String channel_id) {
		String querySql = "SELECT na.adid,na.adtitle,na.adtext FROM news_ads na,news_extends_firstchannel_ads nfa,news_extends_firstchannel nf where " +
				"nf.channel_id='"+channel_id+"' and na.adid=nfa.adid and nfa.channelid=nf.channelid and na.adtype=1";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getSelectAdsAtFstCh fail !!!" +e.getMessage());
			return null;
		}
	}
	public ArrayList getAllActiveAds() {
		String querySql = "SELECT na.adid,na.adtitle,na.adtext FROM news_ads na where  na.adtype=1";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getAllActiveAds fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public boolean updateChannelIcon(DataMap hashMap) {
		String querySql = "update news_extends_channel set iconid="+ObjectToStringDB(hashMap.getMapData("iconid"))+
				",updatetimer="+ObjectToStringDB(hashMap.getMapData("updatetimer"))+ 
				",isshowtime="+ObjectToStringDB(hashMap.getMapData("isshowtime"))+
				",howshowtime="+ObjectToStringDB(hashMap.getMapData("howshowtime"))+
				",whichtag='"+hashMap.getMapData("whichtag")+"'"+
				",isshowshort="+ObjectToStringDB(hashMap.getMapData("isshowshort"))+
				",isshowicon="+ObjectToStringDB(hashMap.getMapData("isshowicon"))+
				",titlenumber="+ObjectToStringDB(hashMap.getMapData("titlenumber"))+
				",channelurl="+ObjectToStringDB(hashMap.getMapData("channelurl"))+
				" where channel_id="+ObjectToStringDB(hashMap.getMapData("channel_id"));
		try {
			logger.debug("updateChannelIcon sql: "+querySql);
			return execUpdate(querySql);
		} catch (Exception e) {
			logger.info(" updateChannelIcon fail !!!" +e.getMessage());
			return false;
		}
	}
	
	public boolean updateChannelType(DataMap hashMap) {
		String querySql = "update news_extends_firstchannel set channeltype="+ObjectToStringDB(hashMap.getMapData("channeltype"))+" " +
				"where channel_id="+ObjectToStringDB(hashMap.getMapData("channel_id"));
		try {
			logger.debug("updateChannelType sql: "+querySql);
			return execUpdate(querySql);
		} catch (Exception e) {
			logger.info(" updateChannelType fail !!!" +e.getMessage());
			return false;
		}
	}
	
	//set channel ads
	public boolean setChannelAdsAtLastCh(DataMap dataMap,String[] selected_ads)
	{
		String channel_id = dataMap.getMapData("channel_id");
		ArrayList<String> sqlStrList = new ArrayList<String>();
		String sql = "delete from news_extends_channel_ads where channleid=" +
				"(SELECT channleid FROM news_extends_channel where channel_id='"+channel_id+"')";
		sqlStrList.add(sql);
		if (selected_ads != null) {
			for (int i = 0; i < selected_ads.length; i++) {
				String adid = selected_ads[i];
				int adorder = i+1;
				sql = "insert into news_extends_channel_ads values " +
						"((SELECT channleid FROM news_extends_channel where channel_id='"+channel_id+"' )," + adid + "," + adorder + ")";
				sqlStrList.add(sql);
			}
		}
		try {
        	return execTransaction(sqlStrList);
        } catch (Exception e) {
        	logger.info(" setChannelAdsAtLastCh fail !!!" +e.getMessage());
            return false;
        }
	}
	
	
	public boolean setChannelAdsAtFstCh(DataMap dataMap,String[] selected_ads)
	{
		String channel_id = dataMap.getMapData("channel_id");
		ArrayList<String> sqlStrList = new ArrayList<String>();
		String sql = "delete from news_extends_firstchannel_ads where channelid="+
				"(SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"')";
		sqlStrList.add(sql);
		if (selected_ads != null) {
			for (int i = 0; i < selected_ads.length; i++) {
				String adid = selected_ads[i];
				sql = "insert into news_extends_firstchannel_ads values " +
						"((SELECT channelid FROM news_extends_firstchannel where channel_id='"+channel_id+"' )," + adid + ")";
				sqlStrList.add(sql);
			}
		}
		try {
        	return execTransaction(sqlStrList);
        } catch (Exception e) {
        	logger.info(" setChannelAdsAtFstCh fail !!!" +e.getMessage());
            return false;
        }
	}
	
	public String findAllUseridAndEmpid(String spcodeS) {
		String userids = "";
		try {
			sql="select tu.user_id,tu.employee_id from t_employee te join t_user tu on te.employee_id=tu.employee_id where te.sp_code in ("+spcodeS+")";
			String userid=null;
			String empid = null;
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp)
			{
				userid=this.getString(o[0]);
				empid=this.getString(o[1]);
				userids+=userid+"|"+empid+",";
			}
			if(!"".equals(userids)){
				userids=userids.substring(0, userids.length()-1);
        	}
		 }catch (Exception e) {
				logger.error("findAllUserids fail !!!" + e.getMessage());
				e.printStackTrace();
		} 
		if("".equals(userids)){
			userids="";
		}
		return userids;
	}
	
	public String findAllUseridAndEmpidByRoot()
	{
		String userids = "";
		try {
			sql="select tu.user_id,tu.employee_id from t_user tu ";
			String userid=null;
			String empid = null;
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp)
			{
				userid=this.getString(o[0]);
				empid=this.getString(o[1]);
				userids+=userid+"|"+empid+",";
			}
			if(!"".equals(userids)){
				userids=userids.substring(0, userids.length()-1);
        	}
		 }catch (Exception e) {
				logger.error("findAllUserids fail !!!" + e.getMessage());
				e.printStackTrace();
		} 
		if("".equals(userids)){
			userids="";
		}
		return userids;
	}
	
	public boolean checkName(TChannels newch) {
		String channel_name = newch.getChannelName();	
		if(channel_name.toLowerCase().equals("news"))
			return false;
		else
			return true;
//		String querySql = "SELECT * FROM t_channels as t1 where channel_name = " + channel_name;
//		log.debug("querySql="+querySql);
//		try {
//			DataMap map=new DBOperate().queryOneRow(querySql);
//			if(map.size()>0)
//			{
//				return true;
//			}
//		} catch (Exception e) {
//			log.info(" checkName fail !!!" +e.getMessage());
//		}
//		return false;
	}
	
//	public String ObjectToStringDB(Object obj) {
//        try {
//            String str = obj.toString().trim();
//
//            if (str.equals("") || str.equals("null")) {
//                return "null";
//            }
//
//            return "'" + str + "'";
//        } catch (Exception e) {
//            return "null";
//        }
//    }
	 public static boolean StringIsNotNull(Object str) {
	        boolean b = false;
	        try {
	            if (!str.equals("") && !str.equals("null")) {
	                b = true;
	            }
	        } catch (Exception e) {
	        }
	        return b;
	    }

	public  ArrayList getAllMUser(String userids) {
		 sql="select user_id,employee_id,role_id,ctrl_date,user_pwd,auth_tupe,can_access,code from t_user where 1=1 ";
		 if(userids!=null){
			 sql+=" and user_id in ("+userids+")";
		 }
		 sql+=" order by ctrl_date";
		 
        try {
            return queryALLResultSet(sql);
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
	  }
	
	//add 0108
	public  ArrayList getSelectChByUser(String user_id) {
		String querySql = "select tuc.channel_id from t_user tu,t_user_channels tuc where tu.user_id='"+user_id+"' and tu.employee_id=tuc.employee_id";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getSelectChByUser fail !!!" +e.getMessage());
			return null;
		}
	}
	public  ArrayList getAllFirstChs(String user_id) {
		String querySql="select  tc.channel_id  ,tc.service_code,tc.channel_name,tc.channel_comment ,tc.function_name,tc.STATUS ,tc.ordered ,tc.created_date,tc.previous_id ,tc.primal_id ,tc.LEVEL ,tc.channel_type  ,tc.channel_hot_topics ,tc.channel_classifying_label" +"  from t_spcode_channel tsc,t_channels tc where tsc.channelid=tc.channel_id and spcode=(select te.sp_code from t_employee te join t_user tu on te.employee_id=tu.employee_id where user_id='"+user_id+"')";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			logger.info(" getAllFirstChs fail !!!" +e.getMessage());
			return null;
		}
	}
	public  ArrayList getAllFirstChs() {
		String querySql = "SELECT tc.channel_id,tc.service_code,tc.channel_name,tc.channel_comment,tc.function_name,tc.status,tc.ordered,tc.created_date,tc.previous_id,tc.primal_id,tc.level,tc.channel_type,tc.channel_hot_topics,tc.channel_classifying_label" +
				" FROM t_channels tc where level=2";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			log.info(" getAllFirstChs fail !!!" +e.getMessage());
			return null;
		}
	}
	public  ArrayList getAllNotFirstChs() {
		//加order by created_date是让channel排序,因为normal和last混合在一起,页面js有可能先处理last
		//而排序后,normal肯定在last之前
		String querySql = "SELECT channel_id,service_code,channel_name,channel_comment,function_name,status,ordered,created_date,previous_id,primal_id,level,channel_type,channel_hot_topics,channel_classifying_label" +
				" FROM t_channels where level>2 order by created_date";
		try {
			return queryALLResultSet(querySql);
		} catch (Exception e) {
			log.info(" getAllNotFirstChs fail !!!" +e.getMessage());
			return null;
		}
	}
	
	
	public ArrayList getAllNotFirstChs(ArrayList firstChList){
		List<TChannels> tclist2=new ArrayList<TChannels>();
		List<TChannels> tclist3=new ArrayList<TChannels>();
		ArrayList result=new ArrayList();;
		TChannels tc=null;
		try {
			for(int i=0;i<firstChList.size();i++){
				DataMap tmp = (DataMap)firstChList.get(i);
				String chid = (String)tmp.get("channel_id");
				String chname = (String)tmp.get("channel_name");
				tc=new TChannels();
				tc.setChannelId(chid);
				tc.setChannelName(chname);
				tc.setChannelName(chname);
				tc.setFunctionName((String)tmp.get("function_name"));
				tc.setLevel((String)tmp.get("level"));
				tc.setPreviousId((String)tmp.get("previous_id"));
				tclist2.add(tc);
			}
			
			/*this.sql="SELECT tc.* from  t_channels tc where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id !=(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level > 2 order by created_date";
			rs3=stmt.executeQuery(sql);
			while(rs3.next()){
				tc=new TChannels();
				tc.setChannelId(rs3.getString("channel_id"));
				tc.setChannelName(rs3.getString("channel_name"));
				tc.setFunctionName(rs3.getString("function_name"));
				tc.setLevel(rs3.getString("level"));
				tc.setPreviousId(rs3.getString("previous_id"));
				tclist3.add(tc);
			}
			conn.commit(); */
			
			this.sql="SELECT tc.channel_id,tc.channel_name,tc.function_name,tc.level,tc.previous_id from  t_channels tc where primal_id =(select channel_id from t_channels where channel_name='news' and status='ENABLED')  and  previous_id !=(select channel_id from t_channels where channel_name='news' and status='ENABLED') and level > 2 order by created_date";
			List<Object[]> temp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:temp)
			{
				tc=new TChannels();
				tc.setChannelId(this.getString(o[0]));
				tc.setChannelName(this.getString(o[1]));
				tc.setFunctionName(this.getString(o[2]));
				tc.setLevel(this.getString(o[3]));
				tc.setPreviousId(this.getString(o[4]));
				tclist3.add(tc);
			}
			
			if(tclist2!=null && tclist2.size()>0){
				List<TChannels> tc_templist=new ArrayList<TChannels>();
				for(TChannels tc2:tclist2){
					if(tclist3!=null && tclist3.size()>0){
						tc_templist = getTc_templist(tclist3,tc2,tc_templist);
						tc_templist.remove(tc2);
					}
				}
				DataMap dm=null;
				for(TChannels tcc:tc_templist){
					dm=new DataMap();
					dm.put("channel_id", tcc.getChannelId());
					dm.put("channel_name", tcc.getChannelName());
					dm.put("function_name", tcc.getFunctionName());
					dm.put("level", tcc.getLevel());
					dm.put("previous_id", tcc.getPreviousId());
					result.add(dm);
				}
				
			}
		} catch (Exception e) {
			logger.error("getAllNotFirstChs fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return result;
	} 
}
